package auth

import (
	"github.com/gin-gonic/gin"
	v1 "last/app/controllers/v1"
	adminModel "last/app/models/admin"
	"last/app/requests"
	adminRequest "last/app/requests/admin"
	"last/pkg/respose"
	"strconv"
)

type CategoryController struct {
	v1.BaseController
}

// Store 新增
func (cate *CategoryController) Store(c *gin.Context) {
	var params adminRequest.CategoryParams
	err := requests.Validator(&params, c)
	if err != nil {
		respose.Failed(c, err.Error())
		return
	}

	//数据库操作
	var cateModel = &adminModel.Categories{
		Title: params.Title,
		Href:  params.Href,
	}
	resultBool := cateModel.Store(cateModel)
	if !resultBool {
		respose.Failed(c, "创建失败")
		return
	}
	respose.Success(c, "", "创建成功")
}

// List 列表
func (cate *CategoryController) List(c *gin.Context) {
	var cateModel = &adminModel.Categories{}
	page, _ := strconv.Atoi(c.Query("page"))
	pageSize, _ := strconv.Atoi(c.Query("page_size"))
	where := make(map[string]interface{}, 1)
	where["title"] = c.DefaultQuery("title", "")

	err, total, list := cateModel.List(page, pageSize, where)
	if err != nil {
		respose.Failed(c, "数据错误")
		return
	}
	results := make(map[string]interface{})
	results["total"] = total
	results["list"] = list
	respose.Success(c, results, "获取成功")
}

// Show 详情
func (cate *CategoryController) Show(c *gin.Context) {
	id := c.Param("id")
	var cateInfo = adminModel.Categories{}
	err := cateInfo.Show(id, &cateInfo)
	if err != nil || cateInfo.ID < 1 {
		respose.Failed(c, "无此数据")
		return
	}
	respose.Success(c, cateInfo, "获取成功")
}

// Remove 删除
func (cate *CategoryController) Remove(c *gin.Context) {
	id := c.Param("id")
	var cateInfo = adminModel.Categories{}
	err := cateInfo.Remove(id, &cateInfo)
	if err != nil {
		respose.Failed(c, "删除失败")
		return
	}
	respose.Success(c, "", "删除成功")
}

// Edit 更新
func (cate *CategoryController) Edit(c *gin.Context) {
	var params adminRequest.CategoryParams

	err := requests.Validator(&params, c)
	if err != nil {
		respose.Failed(c, err.Error())
		return
	}
	editData := make(map[string]interface{})
	editData["title"] = params.Title
	editData["href"] = params.Href
	//数据库操作
	var cateModel = &adminModel.Categories{}
	updateResult := cateModel.Edit(params.Id, editData)
	if updateResult != nil {
		respose.Failed(c, updateResult.Error())
		return
	}
	respose.Success(c, "", "更新成功")
}
